package view.servlet;

import com.alibaba.fastjson.JSONObject;
import entity.Attraction;
import entity.Route;
import entity.User;
import service.AttractionService;
import service.OrderService;
import service.RouteService;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
    private UserService userService;
    private AttractionService attractionService;
    private OrderService orderService;
    private RouteService routeService;
    @Override
    public void init() throws ServletException {
        super.init();
        userService = new UserService();
        attractionService = new AttractionService();
        orderService = new OrderService();
        routeService = new RouteService();
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String methodName = req.getParameter("methodName");
        //通过反射调用不同的方法
        try {
            Method method = this.getClass().getDeclaredMethod(methodName,
                    HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, req, resp);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 用户注册
     */
    private void register(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("用户注册");
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        String phone = req.getParameter("phone");
        String realName = req.getParameter("realName");
        String idNumber = req.getParameter("idNumber");
        String belongPlace = req.getParameter("belongPlace");
        User user = new User(idNumber, userName, password, phone, realName, belongPlace);
        System.out.println(user);
        int rows = userService.register(user);
        PrintWriter out = resp.getWriter();
        if(rows == 1){
            out.print("注册成功！");
        }else{
            out.print("注册失败！");
        }
    }

    /**
     * 用户登录
     */
    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        String idNum = userService.login(userName, password);
        PrintWriter out = resp.getWriter();
        if(idNum == null){
            out.print("登陆失败");
        }else{
            //存储到Session中
            req.getSession().setAttribute("idNum", idNum);
            req.getSession().setAttribute("userName", userName);
            out.print("登陆成功");
        }
    }

    /**
     * 获取一个景点列表
     */
    private void getAttractionList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter pw = resp.getWriter();
        System.out.println("getAll");
        List<Attraction> attractions = attractionService.selectAll();
        String jsonOutput = JSONObject.toJSONString(attractions);
        pw.print(jsonOutput);
    }

    /**
     * 查询指定id的景点详情
     */
    private void getAttractionDetail(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String condition = req.getParameter("condition");
        PrintWriter pw = resp.getWriter();
        Attraction attraction = attractionService.selectById(Integer.parseInt(condition));
        String jsonOutput = JSONObject.toJSONString(attraction);
        pw.print(jsonOutput);
    }

    /**
     * 添加订单
     */
    private void addOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setCharacterEncoding("UTF-8");
        //检查登录状态
        Object o = req.getSession().getAttribute("userName");
        if(o==null || o.equals("")){
            resp.getWriter().print("请先登录");
            return;
        }
        String userName = (String)o;
        String type = req.getParameter("type");
        boolean res=false;
        if(type.equals("旅游景点")) {
            res = orderService.addOrder(userName, req.getParameter("productName"), type,
                    Float.parseFloat(req.getParameter("price")));
        }else if(type.equals("旅游路线")){
            int id = Integer.parseInt(req.getParameter("routeId"));
            Route route = routeService.getRouteById(id);
            res = orderService.addOrder(userName, route.getTitle(), type, route.getPrice());
        }
        if(res){
            resp.getWriter().print("预订成功！");
        }else{
            System.out.println("添加失败");
            resp.getWriter().print("预订失败！");
        }
    }

    /**
     * 查看我的订单
     */
    private void seeMyOrders(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //检查登录状态
        Object o = req.getSession().getAttribute("userName");
        if(o==null || o.equals("")){
            resp.getWriter().print("请先登录");
            return;
        }
        String userName = (String)o;
        List<Map<String, Object>> orders = orderService.queryOrderByUserName(userName);
        String jsonOutput = JSONObject.toJSONString(orders);
        System.out.println(jsonOutput);
        resp.getWriter().print(jsonOutput);
    }

    /**
     * 获取旅游路线列表
     */
    private void getRouteList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter pw = resp.getWriter();
        System.out.println("getAllRoute");
        List<Route> routes = routeService.getAll();
        String jsonOutput = JSONObject.toJSONString(routes);
        pw.print(jsonOutput);
    }

    /**
     * 支付订单
     */
    private void pay(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //能请求到这里说明已经登陆了，可以不用再检查登录状态
        req.setCharacterEncoding("UTF-8");
        //设置发送到客户端响应的内容类型
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        int id = Integer.parseInt(req.getParameter("id"));
        boolean res = orderService.pay(id);
        if(res){
            out.print("true");
        }else{
            out.print("false");
        }
    }

    /**
     * 撤销订单
     */
    private void revocation(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //能请求到这里说明已经登陆了，可以不用再检查登录状态
        req.setCharacterEncoding("UTF-8");
        //设置发送到客户端响应的内容类型
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        int id = Integer.parseInt(req.getParameter("id"));
        boolean res = orderService.revocation(id);
        if(res){
            out.print("true");
        }else{
            out.print("false");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
